package com.example.videopager

import android.media.MediaPlayer
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.SurfaceHolder
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import kotlinx.android.synthetic.main.fragment_player.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

//视频播放的页面
class PlayerFragment(private val url:String) : Fragment() {

    private val mediaPlayer = MediaPlayer()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_player, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //视频播放器类
        mediaPlayer.apply {

            //播放前的监听
            setOnPreparedListener {
                //视频播放的总长度
                progressBarH.max = mediaPlayer.duration
                //不能马上播放，否则出现多个视频播放的声音
                //it.start()
                seekTo(1)
                //视频缓冲加载完成，隐藏转动进度条
                progressBar.visibility = View.INVISIBLE
            }

            //设置视频播放源的地址
            setDataSource(url)

            prepareAsync()

            //视频缓冲时，显示转动进度条
            progressBar.visibility = View.VISIBLE
        }

        //协程,每隔0.5s更新视频播放的进度
        lifecycleScope.launch {
            while (true){
                progressBarH.progress = mediaPlayer.currentPosition
                delay(500)
            }
        }


        //加上这个才能播放视频的画面，否则只能听到声音
        surfaceView.holder.addCallback(object : SurfaceHolder.Callback{
            override fun surfaceChanged(p0: SurfaceHolder, p1: Int, p2: Int, p3: Int) {
                mediaPlayer.setDisplay(p0)

                //视频不要关闭
                mediaPlayer.setScreenOnWhilePlaying(true)
            }

            override fun surfaceDestroyed(p0: SurfaceHolder) {
                //TODO("Not yet implemented")
            }

            override fun surfaceCreated(p0: SurfaceHolder) {
                //TODO("Not yet implemented")
            }

        })
    }


    //保证滑到的视频才播放，否则出现在一个页面出现多个视频播放的声音
    override fun onResume() {
        super.onResume()
        mediaPlayer.start()
        //守护进程,确保第一个视频能播放
        lifecycleScope.launch {
            //如果视频未播放
            while (!mediaPlayer.isPlaying){
                mediaPlayer.start()
                delay(500)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        mediaPlayer.pause()
    }
}